<template>
  <y-dialog ref="dialogRef" v-bind="dialogOptions" @ok="handleOk">
    <section class="h-full flex gap-2 *:h-full">
      <!-- 已选中数据 -->
      <div class="flex-none w-[250px]">
        <div class="border rounded flex flex-col h-full">
          <div class="bg-[#F8F8F9] py-2 border-b px-[10px]">
            已选中
            <span class="text-blue-500 mx-1 font-bold text-sm">
              {{ selectedCollections.length }}
            </span>
            条数据
          </div>
          <transition-group
            tag="ul"
            name="slide"
            class="flex-1 overflow-auto flex flex-col divide-y"
          >
            <li
              v-for="(item, index) in selectedCollections"
              :key="item[keyField]"
              class="flex items-center px-[10px] py-2 hover:bg-[#F5F7FA]"
            >
              <span class="flex-1 line-clamp-1">{{ item[displayField] }}</span>
              <div
                @click="deleteRow(item)"
                class="px-4 pl-8 cursor-pointer text-red-500"
              >
                <svg-icon
                  icon-class="vxe-icon-delete-fill"
                  size="0.75lh"
                ></svg-icon>
              </div>
            </li>
          </transition-group>
        </div>
      </div>
      <div class="flex-1 overflow-hidden">
        <div class="border rounded flex flex-col h-full">
          <div class="bg-[#F8F8F9] py-2 border-b px-[10px]">数据列表</div>
          <div class="flex-1 overflow-auto">
            <y-table
              ref="gridRef"
              v-bind="comListOptions"
              @radio-change="radioChangeEvent"
              @checkbox-change="checkboxChangeEvent"
            ></y-table>
          </div>
        </div>
      </div>
    </section>
  </y-dialog>
</template>

<script>
import { cloneDeep } from '@/utils'

export default {
  name: 'Popup',
  props: {
    // 标题
    title: {
      type: String,
      default: '请选择'
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false
    },
    // 表格配置
    listOptions: Object,
    displayField: {
      type: String,
      required: true
    },
    // 值字段（关键字段）
    valueField: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      // 选中集合
      selectedCollections: []
    }
  },
  computed: {
    // 弹窗配置
    dialogOptions() {
      return {
        title: this.title,
        width: '66%',
        height: '100%'
      }
    },
    // 表格唯一关键字
    keyField() {
      return this.valueField
    },
    // 实际使用表格配置
    comListOptions() {
      // 根据 multiple 确定第一列是单选还是多选
      const type = this.multiple ? 'checkbox' : 'radio'
      const typeConfig = this.multiple
        ? {
            checkboxConfig: {
              trigger: 'row'
            }
          }
        : {
            radioConfig: {
              trigger: 'row'
            }
          }
      if (!this.listOptions) return {}
      return {
        ...this.listOptions,
        tableOptions: {
          ...this.listOptions.tableOptions,
          rowConfig: {
            keyField: this.valueField
          },
          size: 'mini',
          ...typeConfig,
          toolbarConfig: {
            enabled: false
          },
          columns: [
            { type: type, width: 70 },
            ...this.listOptions.tableOptions.columns
          ]
        }
      }
    }
  },
  methods: {
    // 打开弹窗
    async open(selectedCollections = []) {
      // 防御性编程：仅在组件存活时操作
      if (!this.$refs.dialogRef) return

      this.selectedCollections = cloneDeep(selectedCollections)

      try {
        await this.$nextTick()
        if (!this.$refs.dialogRef) return
        this.$refs.dialogRef.open()

        await this.$nextTick()
        if (this.$refs.gridRef) {
          await this.$refs.gridRef.loadData()
          await this.$nextTick()
          this.setSelectedCollections()
        }
      } catch (error) {
        console.error('Dialog open error:', error)
        // 可选：添加用户错误通知
      }
    },
    // 设置选中行 - 单选
    setSelectedCollections() {
      if (
        Array.isArray(this.selectedCollections) &&
        this.selectedCollections.length > 0 &&
        this.selectedCollections[0]?.[this.keyField] !== undefined &&
        this.$refs.gridRef
      ) {
        if (this.multiple) {
          this.selectedCollections.forEach((row) => {
            this.$refs.gridRef.setCheckboxRow(row)
          })
        } else {
          this.$refs.gridRef.setRadioRow(this.selectedCollections[0])
        }
      }
    },
    /**
     * 处理确认操作
     * 1. 关闭通过dialogRef引用的对话框组件
     * 2. 向父组件触发'ok'事件，并携带当前选中的行数据
     */
    handleOk() {
      try {
        this.$refs.dialogRef?.close()
        this.$emit('ok', this.selectedCollections)
      } catch (e) {
        console.error('处理确认操作时发生异常:', e)
      }
    },

    //
    async deleteRow(row = {}) {
      let selectedCollections = cloneDeep(this.selectedCollections)
      if (this.multiple) {
        // 多选
        if (row[this.keyField]) {
          selectedCollections.forEach((item, index) => {
            if (item[this.keyField] === row[this.keyField]) {
              // 取消选中行
              this.$refs.gridRef.setCheckboxRow(item, false)
              selectedCollections.splice(index, 1)
            }
          })
        }
      } else {
        // 单选
        this.$refs.gridRef.clearRadioRow()
        selectedCollections = []
      }
      this.selectedCollections = selectedCollections
    },
    radioChangeEvent(e) {
      this.selectedCollections = this.$refs.gridRef.selectRow
        ? [this.$refs.gridRef.selectRow]
        : []
    },
    checkboxChangeEvent(e) {
      this.selectedCollections = this.$refs.gridRef.selectRows
    }
  }
}
</script>

<style lang="scss" scoped>
// 方案二滑动样式
.slide-move {
  transition: transform 0.3s;
}
.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s;
  max-height: 60px; /* 根据实际行高调整 */
}
.slide-enter-from {
  opacity: 0;
  transform: translateY(-20px);
}
.slide-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>
